<?php

namespace app\api\logic;

use app\api\service\QuestionService;
use app\common\exception\BusinessException;
use app\common\model\CollectCourse;
use app\common\model\Course;
use think\facade\Db;

class VipCourse
{
    /**
     * VIP课程列表
     * @param $param
     * @return array
     */
    public function getList($param): array
    {
        // 提取参数
        $profession_id = $param['professions_id'];

        // 查询条件
        $where = [
            ['a.profession_id', '=', $profession_id],
            ['b.status', '=', 1]
        ];

        // 输出字段
        $field = 'a.course_id,b.code,b.name';

        // 查询数据
        $list = app(\app\common\model\ProfessionCourse::class)
            ->alias('a')
            ->leftJoin('course b', 'a.course_id = b.id')
            ->field($field)
            ->where($where)
            ->select();
        $list = $list ? $list->toArray() : [];

        // 提取题目数量字典
        $courseIds = array_column($list, 'course_id');
        if ($courseIds) {
            $question_static = app(QuestionService::class)->getQuestionStaticByCourseId($courseIds, 2, 1);
            $question_static = array_dict($question_static, 'course_id');
        }

        //处理数据
        foreach ($list as $key => $val) {
            $list[$key]['count'] = $question_static[$val['course_id']]['count'] ?? 0;
        }

        //返回
        return $list;
    }

    /**
     * VIP课程产品列表
     * @param $param
     * @return array
     */
    public function getProductList($param): array
    {
        //提取参数
        $userId = $param['userId'];
        $profession_id = $param['professions_id'];

        //查询条件
        $where = [];

        //查询专业对应课程
        $subWhere = [['profession_id', '=', $profession_id]];
        $subSql = app(\app\common\model\ProfessionCourse::class)->field('course_id')->where($subWhere)->buildSql();;
        $where[] = ['', 'exp', Db::raw("id in$subSql")];

        //剔除已购买课程
        $subWhere = [['user_id', '=', $userId], ['profession_id', '=', $profession_id]];
        $subSql = app(\app\common\model\VipCourse::class)->field('course_id')->where($subWhere)->buildSql();;
        $where[] = ['', 'exp', Db::raw("id not in$subSql")];

        //输出字段
        $field = 'id,code,name,price';

        //查询数据
        $list = app(Course::class)
            ->field($field)
            ->where($where)
            ->select();
        $list = $list ? $list->toArray() : [];
        foreach ($list as $key => $val) {
            $list[$key]['locked'] = 1;
        }
        return $list;
    }
}